// Copyright 2017 Baidu Inc. All Rights Reserved.
// Author: Su Hao (suhao@baidu.com)
//
// Description: Handler

#include "baidu_ca_handler.h"
#include "baidu_ca_adapter.h"
#include "heap_monitor.h"
#include "baidu_measure_stack.h"
#include "duer_log.h"

#define SCHEDULER_STACK_SIZE        (1024 * 5)

namespace duer {

Handler::Handler() : _thread(osPriorityNormal, SCHEDULER_STACK_SIZE), _listener(NULL) {
    _thread.start(this, &Handler::loop);
#ifdef BAIDU_STACK_MONITOR
    register_thread(&_thread, "Handler");
#endif
}

Handler::~Handler() {
    _thread.terminate();
#ifdef BAIDU_STACK_MONITOR
    unregister_thread(&_thread);
#endif
}

void Handler::send_message(int what, void* object) {
    _queue.put(NEW(CA) Message(what, object));
}

void Handler::send_message(const Message& message) {
    _queue.put(NEW(CA) Message(message));
}

void Handler::set_on_message_listener(OnMessageListener* listener) {
    _listener = listener;
}

void Handler::handle_message(Message& message) {
}

void Handler::loop() {
    Message* msg = NULL;
    osEvent evt;

    while (1) {
        evt = _queue.get();

        if (evt.status != osEventMessage) {
            DUER_LOGV("evt.status: %d", evt.status);
            continue;
        }

        msg = reinterpret_cast<Message*>(evt.value.p);

        if (msg) {
            DUER_LOGV("thread: id = %x, used = %d, max = %d, _what = %d",
                 _thread.gettid(), _thread.used_stack(), _thread.max_stack(), msg->get_what());

            if (_listener == NULL || !_listener->on_message(*msg)) {
                handle_message(*msg);
            }

            delete msg;
        }
    }
}

} // namespace duer
